package com.zhouliang.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhouliang.error.DouyinException;
import com.zhouliang.error.StatusCode;
import com.zhouliang.login.dao.UserDao;
import com.zhouliang.login.model.User;
import com.zhouliang.login.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl extends ServiceImpl<UserDao, User> implements LoginService {
    @Autowired
    private UserDao userDao;


    @Override
    public Long registerUser(String name, String password) throws Exception {
        boolean exists = userDao.exists(new QueryWrapper<User>().eq("name", name));
        //验证是否存在用户名
        if (exists) {
            throw new DouyinException(StatusCode.REGISTERERROR);
        }
        userDao.insert(User.builder()
                .name(name)
                .password(password)
                .build());
        User user = userDao.selectOne(new QueryWrapper<User>().eq("name", name));
        return user.getId();
    }

    @Override
    public void loginUser(String name, String password) throws Exception{
        User user = userDao.selectOne(new QueryWrapper<User>().eq("name", name));
        if(user == null || !user.getPassword().equals(password)){
            throw new DouyinException(StatusCode.LOGINERROR);
        }
    }
}
